package com.boyiis.sell.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.ui.Model;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class WeixinUtil {
    public static final String APPID = "wx4e14914506b7d363";
    public static final String APPSECRET = "a04f41419138d8aa8b9e02f6173af1f2";

    public static Map<String, Object> get(String url) {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);

            log.info("executing request " + httpget.getURI());
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                log.info("--------------------------------------");
                // 打印响应状态
                log.info(response.getStatusLine().toString());
                String entityStr = "";
                if (entity != null) {
                    // 打印响应内容长度
                    log.info("Response content length: " + entity.getContentLength());
                    // 打印响应内容
                    entityStr = EntityUtils.toString(entity, "UTF-8");//EntityUtils.toString(entity)每个方法内只能使用一次,不然会抛异常
                    log.info("Response content: " +  entityStr);
                }
                log.info("------------------------------------");
                ObjectMapper mapper = new ObjectMapper();
                HashMap<String,Object> map = mapper.readValue(entityStr,new TypeReference<HashMap<String,Object>>(){});
                return map;
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
